/**
 * 工具类
 */
import Vue from 'vue'
import CryptoJS from 'crypto-js'
import axios from "axios";
import * as Cookies from "tiny-cookie";
import router from "../router";
import qs from "qs"
import {Toast} from 'vue-ydui/dist/lib.rem/dialog';
class UNTIL {//加密
  encrypt(word, keyStr){ 
    keyStr = keyStr ? keyStr : 'secretKey_#water';
    var key  = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return encrypted.toString();
  }
  //解密
  decrypt(word, keyStr){  
    keyStr = keyStr ? keyStr : 'secretKey_#water';
    var key  = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
    var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
  }
  constructor(){
    this.$http = axios.create({
      baseURL: "/",
      headers: {"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"},
      // headers:{"ttsx_auth_token": TOKEN,"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"},
      //`transformResponse`选项允许我们在数据传送到`then/catch`方法之前对数据进行改动
      transformResponse:[function(data){
        //在这里根据自己的需求改变数据
        // layer.close(loading);
        var temData = JSON.parse(data);
        if(temData.code == '200'){
          return temData.data
        }else if(temData.code == '500'){
          Toast({
              mes: temData.msg,
              timeout: 1500
          });
        }else{
          router.replace('/login')
        }
        // return temData;
      }],
      transformRequest:[function(data){
          //在这里根据自己的需求改变数据
         var obj= qs.stringify(data)
         return obj
      }],
    }) 
    this.$http.interceptors.request.use(function(config){
      let TOKEN = localStorage.getItem("ydtoken");
      if (!TOKEN || TOKEN == 'null' || TOKEN == 'undefined') {
        router.replace({path:'/login'});
      }
      config.headers['Authorization'] = 'Bearer '+TOKEN;
      return config;
    },function(err){
      return Promise.reject(err);
    });
  }

}
export default new UNTIL()